<template>
  <div>
    <div class="context-menu-wrapper" v-show="visible" :style="menuStyles">
      <ul>
        <li v-for="item in items" :key="item.command" @click="handleClick(item)">
          {{ item.text }}
        </li>
      </ul>
    </div>
    <div @contextmenu.prevent="showMenu" @click="hideMenu">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, toRefs } from "vue";

export default defineComponent({
  name: "ContextMenu",
  props: {
    items: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const visible = ref(false);
    const x = ref(0);
    const y = ref(0);

    const showMenu = (event) => {
      event.preventDefault();
      visible.value = true;
      x.value = event.clientX;
      y.value = event.clientY;
    };

    const hideMenu = () => {
      visible.value = false;
    };

    const handleClick = (item) => {
      emit("command", item.command);
      hideMenu();
    };

    const menuStyles = {
      left: `${x.value}px`,
      top: `${y.value}px`,
    };

    return {
      ...toRefs(props),
      visible,
      x,
      y,
      showMenu,
      hideMenu,
      handleClick,
      menuStyles,
    };
  },
});
</script>
